package com.ocom.mqsubsidy.business.subsidydataaddperson;

import com.alibaba.fastjson.JSON;
import com.ocom.common.request.payconfig.AddSubsidyDataByPersonRequest;
import com.ocom.mqsubsidy.config.SubsidyDataAddPersonConfig;
import com.ocom.mqsubsidy.feign.PayConfigClientService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Map;

@Component
public class SubsidyDataAddPersonConsumerMqListener {

    private Logger logger = LoggerFactory.getLogger(SubsidyDataAddPersonConsumerMqListener.class);

    @Autowired
    private PayConfigClientService payConfigClientService;

    /**
     * 把该监听命名为A监听
     * 监听队列  远程服务支付接口发送消息  该队列会接受
     * [message, headers, channel]
     * @return {@link }
     * @throws
     */
    @RabbitListener(queues = SubsidyDataAddPersonConfig.SUBSIDYDATAADDPERSON_QUEUE)
    public void process(Message message, @Headers Map<String, Object> headers, Channel channel) throws Exception {
        logger.info("增加补贴人员 消费中");
        logger.info("message【{}】", message);
        String humanMessage = new String(message.getBody(), StandardCharsets.UTF_8);
        //TODO 数据库操作样例
        logger.info("SubsidyDataAddPerson-start:【{}】", humanMessage);
        logger.info("System.currentTimeMillis()【{}】", System.currentTimeMillis());


        AddSubsidyDataByPersonRequest addSubsidyDataByPersonRequest = JSON.parseObject(humanMessage,AddSubsidyDataByPersonRequest.class);
        try {
            payConfigClientService.addSubsidyDataByPerson(addSubsidyDataByPersonRequest);
        } catch (Exception e) {
            logger.info("SubsidyDataAddPerson-出现异常队列消息开始进入死信队列{{}}",e);
        }

        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        logger.info("SubsidyDataAddPerson-end:【{}】",humanMessage);
        logger.info("System.currentTimeMillis()【{}】",System.currentTimeMillis());
    }


    /**
     * 把该监听命名为B监听
     * 监听死信队列  远程服务支付接口发送消息  该队列会接受
     * [message, headers, channel]
     * @return {@link }
     * @throws
     */
    @RabbitListener(queues =  SubsidyDataAddPersonConfig.SUBSIDYDATAADDPERSON_DIE_QUEUE)
    public void processForDie(Message message, @Headers Map<String, Object> headers, Channel channel) throws Exception {
        //死信队列放弃
        channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        logger.info("增加补贴人员-死信队列放弃 ， 【{}】",message);
    }
}
